package com.link.base.base.serviceprojectnew.service;

import com.link.base.base.serviceprojectnew.dao.mybatis.mapper.ServiceProjectMapper;
import com.link.base.base.serviceprojectnew.model.PendingTaskReport;
import com.link.base.base.serviceprojectnew.model.ProjectReport;
import com.link.base.base.serviceprojectnew.model.ServiceProject;
import com.link.base.base.user.model.User;
import com.link.base.base.user.service.UserService;
import com.link.base.basic.service.BasicCommonService;
import com.link.base.tencent.corpwx.agent.model.Agent;
import com.link.base.tencent.corpwx.agent.service.AgentService;
import com.link.base.tencent.corpwx.agent.util.AgentIdUtil;
import com.link.base.tencent.corpwx.message.model.MessageBase;
import com.link.base.tencent.corpwx.message.service.AgentMessageService;
import com.link.base.tencent.corpwx.usermanage.service.CorpWxUserService;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.DateUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author unknown
 * @date unknown
 */
@Service
public class ServiceProjectServiceImpl extends BasicServiceImpl<ServiceProject> implements ServiceProjectService {
    @Resource
    protected KeyGenerateService keyGenerateService;

    @Resource
    private BasicCommonService basicCommonService;

    @Resource
    private ServiceProjectMapper serviceProjectMapper;

    @Resource
    private UserService userService;

    @Resource
    private AgentMessageService agentMessageService;

    @Resource
    private AgentService agentService;

    @Resource
    private CorpWxUserService corpWxUserService;

    @Override
    public BasicMapper<ServiceProject> getBasicMapper() {
        return serviceProjectMapper;
    }

    @Override
    public List<User> queryProjSrproUserPage(User user) throws Exception {

        return serviceProjectMapper.queryProjSrproUserPage(user);
    }

    @Override
    public List<User> queryProjRespUserPage(ServiceProject sp) throws Exception {

        return serviceProjectMapper.queryProjRespUserPage(sp);
    }

    @Override
    public void pushMsgToRelatedUser(String message, Long userId) throws Exception {

        // pushService.pushToUser(message, userId);
    }

    /**
     * 查询项目管理报表
     *
     * @param sp
     * @return JsonObject
     */
    @Override
    public List<ProjectReport> queryProjStatusReport(ServiceProject sp) throws Exception {
//      return serviceProjectMapper.queryProjStatusReport(sp);
        return serviceProjectMapper.queryProjStatusReportPage(sp);
    }


    @Override
    public List<ServiceProject> queryPublishTasksList(ServiceProject t) throws Exception {
        return serviceProjectMapper.queryPublishTasksList(t);
    }

    @Override
    public void ServiceProjectPubStatusUpdate(ServiceProject sp) throws Exception {
        serviceProjectMapper.ServiceProjectPubStatusUpdate(sp);
    }

    @Override
    @Transactional(rollbackFor = {ServiceException.class})
    public void insertMission(ServiceProject t) throws Exception {
        // 新建任务反馈
        serviceProjectMapper.insertMission(t);
        // 任务新建成功之后，给责任人对应的企业微信账号推送消息提醒
        User proposeUser = userService.queryById(t.getProposerId());
        User liableUser = userService.queryById(t.getResponserId());
        String message = "";
        message = message.concat("<div class=\"gray\">" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm") + "</div> ");
        message = message.concat("<div>【" + proposeUser.getFirstName() + "】提出了新的任务: 【"  + t.getAbstracts() + "】</div>");
        message = message.concat("<div class=\"highlight\">请及时跟进，祝工作顺利！</div>");
        // 调用消息推送方法
        this.sendMsgToEnterpriseWechatUser(liableUser, t.getId(), "你有新的任务需要处理", message);
    }

    /**
     * 重写insert方法，用于在新建后添加企业微信消息推送功能
     *
     * @author xieyuqiang
     * @date 2019/3/22 09:46
     */
    @Override
    @Transactional(rollbackFor = {ServiceException.class})
    public void insert(ServiceProject t) throws Exception {
        super.beforInsert(t);
        super.beforUpsert(t);
        super.postDefaultValue(t);
        if (null == t.getId()) {
            t.setId(this.keyGenerateService.keyGenerate());
        }
        if (!super.checkData(t)) {
            throw new ServiceException("PUBLIC-001");
        } else {
            serviceProjectMapper.insert(t);
            super.afterInsert(t);
        }
        // 任务新建成功之后，给责任人对应的企业微信账号推送消息提醒
        User proposeUser = userService.queryById(t.getProposerId());
        User liableUser = userService.queryById(t.getResponserId());
        String message = "";
        message = message.concat("<div class=\"gray\">" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm") + "</div> ");
        message = message.concat("<div>【" + proposeUser.getFirstName() + "】提出了新的任务: 【"  + t.getAbstracts() + "】</div>");
        message = message.concat("<div class=\"highlight\">请及时跟进，祝工作顺利！</div>");
        // 调用消息推送方法
        this.sendMsgToEnterpriseWechatUser(liableUser, t.getId(), "你有新的任务需要处理", message);
    }

    /**
     * 重写update方法，用于在更新后添加企业微信消息推送功能
     *
     * @author xieyuqiang
     * @date 2019/3/22 09:46
     */
    @Override
    @Transactional(rollbackFor = {ServiceException.class})
    public void update(ServiceProject t) throws Exception {
        super.beforUpdate(t);
        super.beforUpsert(t);
        if (!super.checkData(t)) {
            throw new ServiceException("PUBLIC-001");
        } else {
            super.checkId(t);
            // 获取未更新前的任务记录
            ServiceProject beforeUpTask = this.queryById(t);
            // 更新
            Integer returnStatus = serviceProjectMapper.update(t);
            if (returnStatus <= 0) {
                throw new ServiceException("SERVICEREQUESTNEW-004");
            } else {
                // 获取更新后的任务记录
                ServiceProject afterUpTask = this.queryById(t);
                // 调用处理任务内容更新发送不同企业微信消息方法
                this.sendWechatMsgRelyOnTaskUpdate(beforeUpTask, afterUpTask);
            }
        }
    }

    @Override
    public void sendWechatMsgRelyOnTaskUpdate(ServiceProject beforeUpTask, ServiceProject afterUpTask) {
        try {
            // 获取更新前的状态，优先级，严重性，任务内容，负责人
            String oldStatus = basicCommonService.getLovByNameAndType("SERVICE_STATUS", beforeUpTask.getStatus()).getName();
            String oldPriority = basicCommonService.getLovByNameAndType("SER_PRIORITY_LEVEL", beforeUpTask.getPriorityLevel()).getName();
            String oldSeverity = basicCommonService.getLovByNameAndType("SER_SEVERITY_LEVEL", beforeUpTask.getSeverityLevel()).getName();
            String oldContent = beforeUpTask.getAbstracts();
            Long oldLiablePerson = beforeUpTask.getResponserId();
            // 获取更新后的状态，优先级，严重性，任务内容，提出人，负责人
            String newStatus = basicCommonService.getLovByNameAndType("SERVICE_STATUS", afterUpTask.getStatus()).getName();
            String newPriority = basicCommonService.getLovByNameAndType("SER_PRIORITY_LEVEL", afterUpTask.getPriorityLevel()).getName();
            String newSeverity = basicCommonService.getLovByNameAndType("SER_SEVERITY_LEVEL", afterUpTask.getSeverityLevel()).getName();
            String newContent = afterUpTask.getAbstracts();
            Long newProposePerson = afterUpTask.getProposerId();
            Long newLiablePerson = afterUpTask.getResponserId();
            // 获取最后更新人
            Long lastUpdatedBy = afterUpTask.getLastUpdatedBy();
            // 是否含有以下更新标识
            Boolean UpdatedFlag = false;
            // 生成任务提醒消息内容
            String msgContent = "";
            msgContent = msgContent.concat("<div class=\"gray\">" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm") + "</div> ");
            msgContent = msgContent.concat("<div>任务【" + oldContent + "】</div>");
            // 判断任务内容是否发生改变
            if (!oldContent.equals(newContent)) {
                UpdatedFlag = true;
                msgContent = msgContent.concat("<div>内容变成了【" + newContent + "】</div>");
            }
            // 判断任务状态是否发生改变
            if (!oldStatus.equals(newStatus)) {
                UpdatedFlag = true;
                msgContent = msgContent.concat("<div>状态由【" + oldStatus + "】变成了【" + newStatus + "】</div>");
            }
            // 判断优先级是否发生改变
            if (!oldPriority.equals(newPriority)) {
                UpdatedFlag = true;
                msgContent = msgContent.concat("<div>优先级由【" + oldPriority + "】变成了【" + newPriority + "】</div>");
            }
            // 判断严重性是否发生改变
            if (!oldSeverity.equals(newSeverity)) {
                UpdatedFlag = true;
                msgContent = msgContent.concat("<div>严重性由【" + oldSeverity + "】变成了【" + newSeverity + "】</div>");
            }
            // 判断负责人是否发生改变
            if (!oldLiablePerson.equals(newLiablePerson)) {
                UpdatedFlag = true;
                User oldLiableUser = userService.queryById(oldLiablePerson);
                User newLiableUser = userService.queryById(newLiablePerson);
                msgContent = msgContent.concat("<div>负责人由【" + oldLiableUser.getFirstName() + "】变成了【" + newLiableUser.getFirstName() + "】</div>");
            }
            // 当有以上内容修改，且存在发送目标，则添加修改人信息
            if ((!newLiablePerson.equals(lastUpdatedBy) || !newProposePerson.equals(lastUpdatedBy)) && UpdatedFlag) {
                User lastUpdUser = userService.queryById(lastUpdatedBy);
                msgContent = msgContent.concat("<div>本次修改人：" + lastUpdUser.getFirstName() + "</div>");
            }
            msgContent = msgContent.concat("<div class=\"highlight\">请知悉，祝工作顺利！</div>");

            // 判断是否需要发送给提出人
            if (!newProposePerson.equals(lastUpdatedBy) && UpdatedFlag) {
                User proposeUser = userService.queryById(newProposePerson);
                // 给提出人发送消息提醒
                this.sendMsgToEnterpriseWechatUser(proposeUser, afterUpTask.getId(), "你提出的任务有变更", msgContent);
            }
            // 判断是否需要发送给负责人
            if (!newLiablePerson.equals(lastUpdatedBy) && UpdatedFlag) {
                User liableUser = userService.queryById(newLiablePerson);
                this.sendMsgToEnterpriseWechatUser(liableUser, afterUpTask.getId(), "你负责的任务有变更", msgContent);
            }
        } catch (Exception e) {
            LCLogger.withException("整理任务更新内容时发生异常：" + e.getMessage());
        }
    }

    @Override
    public void sendMsgToEnterpriseWechatUser(User user, Long taskId, String title, String content) {
        try {
            // 需要推送的企业微信用户列表
            List<String> userIdList = new ArrayList<>();
            // 通讯录的成员ID对应linkcrm系统用户的username
            userIdList.add(user.getUsername());

            // 获取指定企业微信应用信息
            Agent agent = new Agent();
            agent.setAgentId(AgentIdUtil.CORPWX_TASK_MANAGE_AGENTID);
            agent = agentService.queryAgentById(agent);

            // 拼接消息跳转url
            String url = agent.getHomeUrl() + "&moduleType=task-manager-detail&moduleId=" + taskId + "&userId=" + user.getId();

            // 调用企业微信消息推送接口
            MessageBase messageBase = new MessageBase();
            messageBase.setAgentId(AgentIdUtil.CORPWX_TASK_MANAGE_AGENTID);
            messageBase.setUserIdList(userIdList);
            agentMessageService.sendAgentTextCardMsg(messageBase, title, content, url, "查看详情");
        } catch (Exception e) {
            LCLogger.withException("推送企业微信消息异常：" + e.getMessage());
        }
    }

    @Override
    public List<ServiceProject> taskNumberCountByStatus(ServiceProject entity) throws Exception {
        // 获取当前登录用户
        CoreUser user = UserUtil.getUser();

        entity.setLogin(user.getId().toString());

        // 分组统计任务状态的任务数量
        List<ServiceProject> taskList = serviceProjectMapper.groupTaskNumberByStatus(entity);

        return taskList;
    }

    @Override
    public void sendTaskReportForWorkWx() throws Exception {
        // 获取所有满足企业微信推送条件的用户
        List<com.link.base.tencent.corpwx.addressbook.model.User> corpWxUserList
             = corpWxUserService.corpWxUserList(new com.link.base.tencent.corpwx.addressbook.model.User());

        // 获取提出人和负责人的全部、即将延期、已延期的待处理任务统计结果
        List<PendingTaskReport> taskCountList = serviceProjectMapper.countByEndDtAndUser();

        // 要推送的消息内容
        String message;

        // 需要推送的企业微信用户列表
        List<String> userIdList = new ArrayList<>();

        // 获取指定企业微信应用信息
        Agent agent = new Agent();
        agent.setAgentId(AgentIdUtil.CORPWX_TASK_MANAGE_AGENTID);
        agent = agentService.queryAgentById(agent);

        Map<String, String> taskUserMap = new HashMap<>(16);

        // 遍历统计结果生成企业微信消息并推送
        for (PendingTaskReport i : taskCountList) {
            // 生成消息内容
            message = "";
            message = message.concat("<div class=\"gray\">" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm") + "</div> ");
            message = message.concat("<div>你提出的任务中尚有【" + i.getProposeNum() + "】条待处理，其中：</div>");
            message = message.concat("<div>延期任务【" + i.getProposeDelayNum() + "】条</div>");
            message = message.concat("<div>今日到期【" + i.getProposeComeDelayNum() + "】条</div>");
            message = message.concat("<div>你负责的任务中尚有【" + i.getLiableNum() + "】条待处理，其中：</div>");
            message = message.concat("<div>延期任务【" + i.getLiableDelayNum() + "】条</div>");
            message = message.concat("<div>今日到期【" + i.getLiableComeDelayNum() + "】条</div>");
            message = message.concat("<div class=\"highlight\">请及时跟进，祝工作顺利！</div>");

            // 生成当前推送用户
            userIdList.clear();
            userIdList.add(i.getUserName());

            // 记录用户到taskUserMap用以识别暂无任务用户
            taskUserMap.put(i.getUserName(), i.getUserName());

            // 调用企业微信消息推送方法
            try {
                MessageBase messageBase = new MessageBase();
                messageBase.setAgentId(AgentIdUtil.CORPWX_TASK_MANAGE_AGENTID);
                messageBase.setUserIdList(userIdList);
                agentMessageService.sendAgentTextCardMsg(messageBase,i.getFstName() + " 早上好，任务早报温馨提示！", message, agent.getHomeUrl(), "查看详情");
            } catch (Exception e) {
                LCLogger.withException("推送企业微信消息异常：" + e.getMessage());
            }
        }

        // 推送暂无任务消息的用户
        for (com.link.base.tencent.corpwx.addressbook.model.User item: corpWxUserList) {
            if (StringUtils.isBlank(taskUserMap.get(item.getUserId()))) {
                // 调用企业微信消息推送方法
                try {
                    // 生成消息内容
                    message = "";
                    message = message.concat("<div class=\"gray\">" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm") + "</div> ");
                    message = message.concat("<div class=\"highlight\">您今日暂无任务安排，祝工作顺利！</div>");
                    // 生成当前推送用户
                    userIdList.clear();
                    userIdList.add(item.getUserId());
                    MessageBase messageBase = new MessageBase();
                    messageBase.setAgentId(AgentIdUtil.CORPWX_TASK_MANAGE_AGENTID);
                    messageBase.setUserIdList(userIdList);
                    agentMessageService.sendAgentTextCardMsg(messageBase,item.getName() + " 早上好，任务早报温馨提示!", message, agent.getHomeUrl(), "查看详情");
                } catch (Exception e) {
                    LCLogger.withException("推送企业微信消息异常：" + e.getMessage());
                }
            }
        }

    }

    /**
     * 其他系统任务反馈创建
     *
     * @author 李莹
     * @date 2019/12/20 02:06
     * @param entity 任务对象实体，用于接收反馈数据
     */
    @Override
    public ServiceProject openInsertFeedback(ServiceProject entity) throws Exception {
        // 1、通过提出人姓名和责任人姓名查找用户数据，当数据存在，且唯一时，确认用户
        User pUser = new User();
        User rUser = new User();
        if (StringUtils.isNotBlank(entity.getpFirstName())) {
            pUser.setPageFlag(false);
            // 设置用户名称和默认corpid102，查询用户数据
            pUser.setFirstName(entity.getpFirstName());
            pUser.setLoginCorpId(102L);
            List<User> pUsers = userService.queryByExamplePage(pUser);
            if (pUsers.size() == 1) {
                pUser = pUsers.get(0);
                entity.setProposerId(pUser.getId());
            }
        }
        if (StringUtils.isNotBlank(entity.getrFirstName())) {
            rUser.setPageFlag(false);
            rUser.setFirstName(entity.getrFirstName());
            rUser.setLoginCorpId(102L);
            List<User> rUsers = userService.queryByExamplePage(rUser);
            if (rUsers.size() == 1) {
                rUser = rUsers.get(0);
                entity.setResponserId(rUser.getId());
            }
        }

        // 2、保存任务反馈记录
        // 设置attr10，标志该记录为任务管理数据，在项目管理-任务管理查看
        entity.setAttr10("serviceProject");
        // 设置默认数据，状态，优先级，严重性，发布状态，百分比，类型，账套102，创建人，更新人
        entity.setStatus("新建");
        entity.setSeverityLevel("中");
        entity.setPriorityLevel("中");
        entity.setPubStatus("NO PUBLISHED");
        entity.setPercentage("0");
        entity.setType("技术开发");
        entity.setLoginCorpId(102L);
        entity.setCorpid(102L);
        serviceProjectMapper.insertMission(entity);

        // 3、发送企业消息，当匹配到相应责任人时
        if (null != rUser.getId()) {
            String pUserName = "";
            if (StringUtils.isNotBlank(pUser.getFirstName())) {
                pUserName = pUser.getFirstName();
            }
            String message = "";
            message = message.concat("<div class=\"gray\">" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm") + "</div> ");
            message = message.concat("<div>【" + pUserName + "】提出了新的任务: 【"  + entity.getAbstracts() + "】</div>");
            message = message.concat("<div class=\"highlight\">请及时跟进，祝工作顺利！</div>");
            this.sendMsgToEnterpriseWechatUser(rUser, entity.getId(), "你有新的任务需要处理", message);
        }

        return this.queryById(entity);
    }

}
